# -*- coding: utf-8 -*-
"""
-------------------------------------------------
  Description :
  Author :    Administrator
  date：     2021/10/10
-------------------------------------------------
  Change Activity:
          2021/10/10:
-------------------------------------------------
"""
import json
import requests
from binascii import a2b_hex
from Crypto.Cipher import AES
from Api.BookAccountNumberManage.retry_model import MyRetry
from loguru import logger


def decrypt(text):
    key = "%qq123456.".ljust(16, '\0').encode('utf-8')
    iv_b = ("%qq123456.".ljust(16, '\0')).encode('utf-8')
    cryptos = AES.new(key, AES.MODE_CBC, iv_b)
    plain_text = cryptos.decrypt(a2b_hex(text))
    return bytes.decode(plain_text).rstrip('\0')


@MyRetry(times=3, return_obj={})
def get_proxy():
    url = "http://192.168.44.9/get/?token=%qq123456..&qname=spider2&num=1"
    res = requests.get(url).json()
    if res.get('code') == '-1':
        logger.error(res.get('message'))
        return False
    if res.get('code') == '1' and res.get('message') == '获取成功' and res.get('proxy_list'):
        info = json.loads(res.get('proxy_list')[0])
        pw = decrypt(info["password"])
        if info.get('type') == 1:
            proxy = {
                "http": f"http://{info['user']}:{pw}@{info['proxy_ip']}",
                "https": f"https://{info['user']}:{pw}@{info['proxy_ip']}"
            }
        else:
            proxy = {"http": f"http://{info['proxy_ip']}", "https": f"https://{info['proxy_ip']}"}
        return proxy
    else:
        raise


if __name__ == '__main__':
    res = get_proxy()
    print(res)
